 package com.yloveg.controller;




import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections4.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yloveg.base.BaseController;
import com.yloveg.base.WXPayUtil;
import com.yloveg.common.DateUtil;
import com.yloveg.common.HttpUtils;
import com.yloveg.common.IpUtil;
import com.yloveg.entity.VActivity;
import com.yloveg.entity.VGift;
import com.yloveg.entity.VPay;
import com.yloveg.entity.VPayOrder;
import com.yloveg.entity.VPlayer;
import com.yloveg.service.VActivityService;
import com.yloveg.service.VGiftService;
import com.yloveg.service.VPayOrderService;
import com.yloveg.service.VPayService;
import com.yloveg.service.VPlayerService;


@Controller
@RequestMapping({"pay"})  
public class PayController extends BaseController {  
	
	@Autowired
    private VPayService vPayervice;
	
	@Autowired
    private VPayOrderService vPayerOrdervice;
	
	@Autowired
    private VPlayerService vPlayerService;
	
	@Autowired
    private VGiftService vGiftService;
	
	@Autowired
    private VActivityService vActivityService;

	
	@RequestMapping("/createOrder")
    @ResponseBody
    public Map<String, String> createOrder (VPayOrder vPayOrder,HttpServletRequest request) throws Exception {
		Map<String, String> map = new HashedMap<String, String>();
		String orderNo = DateUtil.transPath();
		VGift vGift = vGiftService.selectByPrimaryKey(Integer.valueOf(vPayOrder.getVgiftid()));
		vPayOrder.setOrderNo(orderNo);
		vPayOrder.setMoney(BigDecimal.valueOf(vGift.getPrice()));
		vPayOrder.setVgiftid(vPayOrder.getVgiftid());
		int result = vPayerOrdervice.insert(vPayOrder);
		if(result>0) {
			VPay vp = vPayervice.selectByPrimaryKey(1);
			String appid = vp.getAppid();
			String mch_id  = vp.getMchid();
			String nonce_str  = WXPayUtil.generateNonceStr();
			String body = "votePay";
			String out_trade_no  = orderNo;
			String total_fee  = String.valueOf(BigDecimal.valueOf(vGift.getPrice()).multiply(new BigDecimal(100))).substring(0, String.valueOf(BigDecimal.valueOf(vGift.getPrice()).multiply(new BigDecimal(100))).indexOf("."));
			String spbill_create_ip = IpUtil.getLocalIp(request)+"/";
			spbill_create_ip=spbill_create_ip.substring(0, spbill_create_ip.indexOf("/"));
			String notify_url = vp.getNotifyUrl();
			String trade_type  = "JSAPI";
			Map<String, String> data = new HashMap<String, String>();
			data.put("appid", appid);
			data.put("mch_id", mch_id);
			data.put("nonce_str", nonce_str);
			data.put("body", body);
			data.put("out_trade_no", out_trade_no);
			data.put("total_fee", total_fee);
			data.put("spbill_create_ip", spbill_create_ip);
			data.put("notify_url", notify_url);
			data.put("trade_type", trade_type);
			data.put("openid", vPayOrder.getOpenid());
			System.out.println(data.toString());
			
			String sign = WXPayUtil.generateSignature(data, vp.getPaternerkey());
			data.put("sign", sign);
			System.out.println(data.toString());
			String xml = WXPayUtil.mapToXml(data);
			String wxResult = HttpUtils.doPost("https://api.mch.weixin.qq.com/pay/unifiedorder", xml);
			Map<String, String> wxResultNew = WXPayUtil.xmlToMap(wxResult);
			System.out.println(wxResult);
			String prepay_id = wxResultNew.get("prepay_id");
			map.put("package", "prepay_id="+prepay_id);
			map.put("appId", appid);
			map.put("nonceStr", nonce_str);
			map.put("timeStamp", String.valueOf(WXPayUtil.getCurrentTimestamp()));
			map.put("signType", "MD5");
			String paySign = WXPayUtil.generateSignature(map, vp.getPaternerkey());
			map.put("paySign", paySign);
			System.out.println(map.toString());
		}
		return map;
		
	}
	
	@RequestMapping("callback")
	@ResponseBody
	public String callBack(HttpServletRequest request,HttpServletResponse response){
		//System.out.println("微信支付成功,微信发送的callback信息,请注意修改订单信息");
		InputStream is = null;
		System.out.print("===============================支付回调=======================================");
		try {
			is = request.getInputStream();//获取请求的流信息(这里是微信发的xml格式所有只能使用流来读)
			String xml = WXPayUtil.InputStream2String(is);
			Map<String, String> notifyMap = WXPayUtil.xmlToMap(xml);//将微信发的xml转map
			int result = 0;			
			if(notifyMap.get("return_code").equals("SUCCESS")){  
	                if(notifyMap.get("result_code").equals("SUCCESS")){  
	                String orderNo = notifyMap.get("out_trade_no");//商户订单号 
	                String amountpaid = notifyMap.get("total_fee");//实际支付的订单金额:单位 分
	                BigDecimal amountPay = (new BigDecimal(amountpaid).divide(new BigDecimal("100"))).setScale(2);//将分转换成元-实际支付金额:元
	                //String openid = notifyMap.get("openid");  //如果有需要可以获取
	                //String trade_type = notifyMap.get("trade_type");  
	                
	                /*以下是自己的业务处理*/
	                VPayOrder vPayOrder = vPayerOrdervice.findOrderByOrderNo(orderNo);
	                if(vPayOrder!=null) {
	                	vPayOrder.setPayState("1");
	                	vPayOrder.setMoney(amountPay);
	                	vPayOrder.setPayTime(new Date());
	                	String playerid = vPayOrder.getPlayerid();
	                	VGift vGift = vGiftService.selectByPrimaryKey(Integer.valueOf(vPayOrder.getVgiftid()));
	            		VPlayer	vPlayer = vPlayerService.selectByPrimaryKey(Integer.valueOf(playerid));
	            		int poll = vGift.getVotenum();
	            		if(vPlayer.getPoll()>0) {
	            			vPlayer.setPoll(vPlayer.getPoll()+poll);
	            		}else {
	            			vPlayer.setPoll(poll);
	            		}
	            		VActivity vactivity=vActivityService.selectByPrimaryKeyN(Integer.valueOf(vPayOrder.getActivityid()));
	            		if(vactivity!=null) {
	            			VActivity vactivityt = new VActivity();
	            			vactivityt.setMoneyDay(vactivity.getMoneyDay().add(amountPay));
	            			vactivityt.setMoneySum(vactivity.getMoneySum().add(amountPay));
	            			vactivityt.setThumbnum(vactivity.getThumbnum()+poll);
	            			vactivityt.setId(vactivity.getId());
		            		result = vActivityService.updateByPrimaryKeySelective(vactivityt);
	            		}
	            		vPlayer.setAmount(vPlayer.getAmount()+Double.valueOf(amountPay.toString()));
	            		result = vPlayerService.updateByPrimaryKeySelective(vPlayer);
	                	result = vPayerOrdervice.updateByPrimaryKeySelective(vPayOrder);
	                }
	                  
	            }  
	        }
			if(result!=0) {
		        //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
		        response.getWriter().write("<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>");  				
			}

			is.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
